package com.cetsk.android.talkorigins;

import android.app.ListActivity;
import android.content.Intent;
import android.database.SQLException;
import android.database.sqlite.SQLiteStatement;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ClaimsListActivity extends ListActivity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.claims_list);

		Claim claim = (Claim) getIntent().getSerializableExtra("claim");
		if(claim != null){
			ClaimAdapter ca = new ClaimAdapter(getBaseContext(), R.layout.list_item, ClaimHelper.getClaims(this,claim.getId(), true));
			setTitle(claim.getName());
			getListView().setAdapter(ca);
		}
		ListView lv = getListView();
		lv.setTextFilterEnabled(true);

		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				try{
					Claim claim = (Claim) ((LinearLayout) view).getTag();
					if(claim.getChildren().size() != 0){
						Intent intent = new Intent(parent.getContext(), ClaimsListActivity.class);
						intent.putExtra("claim",claim);
						startActivity(intent);

					} else {
						Intent intent = new Intent(parent.getContext(), ClaimViewActivity.class);
						intent.putExtra("claim",claim);
						startActivity(intent);
					}
				} catch(Exception e){

				}
			}
		});

		lv.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
				AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
				menu.setHeaderTitle("Action");
				int i = 0;
				Claim c = (Claim) info.targetView.getTag();
				try {
					if(c.getChildren().size() > 0){
						menu.add(Menu.NONE, 1, ++i, "View Children");
					}
					if(c.getUrl().length() > 1){
						menu.add(Menu.NONE, 1, ++i, "View Claim");
						menu.add(Menu.NONE, 1, ++i, "Add as Favorite");
						menu.add(Menu.NONE, 1, ++i, "Share");
					}
				} catch (Exception e){
					Log.e("Problem parsing claim",e.toString());
				}
			}
		});
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.layout.main_menu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.favorites:
	    	Intent favIntent = new Intent(getBaseContext(), FavoritesListActivity.class);
			startActivity(favIntent);
	        return true;
	    case R.id.search:
	    	onSearchRequested();
	        return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
    public boolean onContextItemSelected(MenuItem item) {
	    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
		Claim c = (Claim) info.targetView.getTag();
		
		if(item.toString().equals("View Claim")){
			Intent intent = new Intent(info.targetView.getContext(), ClaimViewActivity.class);
			intent.putExtra("claim",c);
			startActivity(intent);
		} else if(item.toString().equals("View Children")) {
			Intent intent = new Intent(info.targetView.getContext(), ClaimsListActivity.class);
			intent.putExtra("claim",c);
			startActivity(intent);
		} else if(item.toString().equals("Add as Favorite")) {
			DatabaseHelper dbh = new DatabaseHelper(this);
			//SQLiteDatabase dbh = this.openOrCreateDatabase(DatabaseHelper.DBNAME, SQLiteDatabase.OPEN_READWRITE, null);
			try {
				SQLiteStatement stmt = dbh.getWritableDatabase().compileStatement("INSERT INTO " + DatabaseHelper.FAVORITES_TABLE + " (Id,ClaimId) VALUES (null,?)");
				stmt.bindLong(1, c.getId());
				stmt.execute();
				Toast.makeText(getApplicationContext(), "Favorite Added", Toast.LENGTH_SHORT).show();
			} catch (SQLException sqle){
				if(sqle.getMessage().startsWith("error code 19:")){
					Toast.makeText(getApplicationContext(), "Could not add favorite, because it already exists!", Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(getApplicationContext(), "Error adding favorite: "+sqle.getMessage(), Toast.LENGTH_SHORT).show();
				}
				Log.e("SQLError",sqle.getMessage());
			} finally {
				dbh.close();
			}
		} else if(item.toString().equals("Share")){
				String url = "http://www.talkorigins.org/indexcc/" + c.getUrl();
				Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
				shareIntent.setType("text/plain");
				shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "TalkOrigins article: " + c.getName());
				shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, url);

				startActivity(Intent.createChooser(shareIntent, "Share via..."));
		} else {
			
		}
    	return true;
    }
}